import { Vue, Component } from 'vue-property-decorator';
import style from '@/styles/views/water.module.less';
import { EapLayout, Hygrometer } from '@/components';
import { edgerosNetSvg, humidifierOffSvg, humidifierOnSvg, waterOffSvg, waterOnSvg } from '@/assets';
import {
  Button,
  Cell,
  CellGroup,
  Dialog,
  Field,
  NavBar,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  Slider,
  Stepper,
  Tag
} from 'vant';
import { IDevice } from '@/interfaces/api.interface';
import _ from 'lodash';
Vue.use(Dialog);

const DEDAULT_FLOWERS = [
  // 模拟数据
  {
    label: '吊兰',
    people: '80%',
    points: [60, 70]
  },
  {
    label: '绿萝',
    people: '78%',
    points: [80, 100]
  },
  {
    label: '常春藤',
    people: '90%',
    points: [50, 70]
  }
];
const PICKER_COLUMNS = ['吊兰', '绿萝', '常春藤'];

@Component({
  components: {
    'eap-layout': EapLayout,
    'van-nav-bar': NavBar,
    'van-tag': Tag,
    'van-cell': Cell,
    'van-field': Field,
    'van-stepper': Stepper,
    'van-button': Button,
    'van-radio-group': RadioGroup,
    'van-radio': Radio,
    'van-cell-group': CellGroup,
    'van-slider': Slider,
    'van-picker': Picker,
    'van-popup': Popup,
    hygrometer: Hygrometer
  },
  sockets: {
    devices(data) {
      this.$data.list = data;
    },
    join(dev) {
      if (dev.report.type === 'device' && dev.report.name === '土壤湿度') {
        this.$data.humidifierId = dev.devid;
      } else if (dev.report.type === 'device' && dev.report.name === '智能浇水') {
        this.$data.waterId = dev.devid;
      }
    },
    lost(dev) {
      if (dev.report.type === 'device' && dev.report.name === '土壤湿度') {
        this.$data.humidifierId = '';
        this.$edger.notify.error('土壤湿度探测设备丢失！');
      } else if (dev.report.type === 'device' && dev.report.name === '智能浇水') {
        this.$data.waterId = '';
        this.$edger.notify.error('智能浇水设备丢失！');
      }
    },
    error(msg) {
      this.$edger.notify.error(msg);
    },
    humidity(data) {
      this.$data.hygrometer = data;
    },
    sceneSettings(data) {
      this.$data.points = data.points;
      const flower = _.find(DEDAULT_FLOWERS, { label: data.label });
      if (flower) {
        this.$data.flower = flower;
      }
    }
  }
})
export default class Water extends Vue {
  private list: IDevice[] = []; // 设备列表
  private humidifierId = ''; // 湿度感应设备id
  private waterId = ''; // 浇水器设备id
  private hygrometer = 93; // 当前湿度值
  private model = {
    show: false,
    type: 'humidifier', // humidifier || water
    title: '湿度检测器'
  };
  private showPicker = false;
  private flower = {
    label: '',
    people: '0%',
    points: [0, 100]
  };
  private points = [60, 100]; // 湿度区间

  // 当前湿度提示浇水状态
  private get waterStatusType() {
    if (this.hygrometer >= this.points[1]) {
      return 'danger';
    } else if (this.hygrometer >= this.points[0] && this.hygrometer < this.points[1]) {
      return 'success';
    } else {
      return 'danger';
    }
  }

  private get waterStatusText() {
    if (this.hygrometer >= this.points[1]) {
      return '湿度超标';
    } else if (this.hygrometer >= this.points[0] && this.hygrometer < this.points[1]) {
      return '湿度正常';
    } else {
      return '湿度干燥';
    }
  }

  public created() {
    this.$socket.client.emit('init');
  }

  public render() {
    return (
      <eap-layout>
        <van-nav-bar title='湿度浇水' slot='header' />
        <div class={style['water']}>
          <div class={[style['water-viewport'], !this.humidifierId && style['water-viewport-disabled']]}>
            <hygrometer v-model={this.hygrometer} points={this.points}></hygrometer>
            <div class={style['water-viewport-content']}>
              <h3>土壤湿度(%)：</h3>
              <p>
                <span>数据值：</span>
                {this.hygrometer}
              </p>
              <p>
                <span>状态：</span>
                <van-tag type={this.waterStatusType} size='medium'>
                  {this.waterStatusText}
                </van-tag>
              </p>
              <div></div>
            </div>
          </div>
          <h4>设备选择：</h4>
          <div class={style['water-dev']}>
            <img
              src={this.humidifierId ? humidifierOnSvg : humidifierOffSvg}
              alt='humidifier'
              on-click={() => this.showModel('humidifier')}
            />
            <i></i>
            <img src={edgerosNetSvg} alt='edgerosNet' />
            <i></i>
            <img src={this.waterId ? waterOnSvg : waterOffSvg} alt='water' on-click={() => this.showModel('water')} />
          </div>
          <h4>数据设定：</h4>
          <van-field
            style={{ 'margin-bottom': '16px' }}
            readonly
            clickable
            label='选择植物'
            value={this.flower.label}
            placeholder='选择培育的植物'
            onclick={() => (this.showPicker = true)}
          />
          <div class={style['slider-container']}>
            <div class={[style['slider-text'], style['slider-text-down']]} style={{ left: this.points[0] + '%' }}>
              {this.points[0]}
            </div>
            <div class={style['slider-text']} style={{ left: this.points[1] + '%' }}>
              {this.points[1]}
            </div>
            <van-slider
              v-model={this.points}
              range
              active-color='#07c160'
              on-change={this.handleSliderChange}
              // on-input={this.handleSliderInput}
              ></van-slider>
          </div>
          {this.flower.label && (
            <div class={style['flower-desc']}>
              {`根据该应用统计：种植${this.flower.label}的有${this.flower.people}的用户控制湿度在 ${this.flower.points[0]}% - ${this.flower.points[1]}% 之间最为适宜`}
            </div>
          )}
        </div>
        {this.renderDevModel()}
        {this.renderFlowerPicker()}
      </eap-layout>
    );
  }

  private renderDevModel() {
    return (
      <van-dialog
        v-model={this.model.show}
        title={this.model.title}
        showConfirmButton={false}
        closeOnClickOverlay
        class={style['model']}>
        <div class={style['model-list']}>{this.renderSelectDevList()}</div>
      </van-dialog>
    );
  }

  private renderSelectDevList() {
    return (
      <van-radio-group value={this.model.type === 'humidifier' ? this.humidifierId : this.waterId}>
        <van-cell-group>
          {this.list.map((item: IDevice) => {
            return (
              <van-cell
                title={item.alias}
                clickable
                on-click={() => {
                  this.selectDevice(item);
                }}>
                <van-radio name={item.devid} slot='right-icon' />
              </van-cell>
            );
          })}
        </van-cell-group>
      </van-radio-group>
    );
  }

  private showModel(type: 'humidifier' | 'water') {
    this.model = {
      type,
      show: true,
      title: type === 'humidifier' ? '湿度检测器' : '浇水设备'
    };
  }

  private renderFlowerPicker() {
    return (
      <van-popup v-model={this.showPicker} round position='bottom'>
        <van-picker
          show-toolbar
          title='选择植物'
          columns={PICKER_COLUMNS}
          on-confirm={this.handlePickerConfirm}
          on-cancel={this.handlePickerCancel}
        />
      </van-popup>
    );
  }

  // 选择场景设备
  private async selectDevice(dev: IDevice) {
    let delete_id = '';
    if (this.model.type === 'humidifier') {
      if (this.humidifierId === dev.devid) {
        return;
      }
      if (dev.report.type !== 'device' || dev.report.name !== '土壤湿度') {
        return this.$edger.notify.error('请选择湿度检测器设备！');
      }
      delete_id = this.humidifierId;
    } else if (this.model.type === 'water') {
      if (this.waterId === dev.devid) {
        return;
      }
      if (dev.report.type !== 'device' || dev.report.name !== '智能浇水') {
        return this.$edger.notify.error('请选择浇水设备！');
      }
      delete_id = this.waterId;
    }
    this.$socket.client.emit('change-scene-devices', { add_id: dev.devid, delete_id });
    this.model.show = false;
  }

  private async handleSliderChange(v: number[]) {
    // if (v[1] - v[0] < 10) {
    //   return;
    // }
    let sceneSettings = { points: v };
    if (this.flower) {
      sceneSettings = { ...this.flower, points: v };
    }
    this.$socket.client.emit('change-scene-settings', sceneSettings);
  }

  // private handleSliderInput(v: number[]) {
  //   // if (v[1] - v[0] < 10) {
  //   //   return;
  //   // }
  //   this.points = v;
  // }

  private async handlePickerConfirm(v: string) {
    const flower = _.find(DEDAULT_FLOWERS, { label: v });
    if (flower) {
      this.$socket.client.emit('change-scene-settings', flower);
      this.handlePickerCancel();
    } else {
      this.$edger.notify.error('操作出现未知错误，请重试！');
    }
  }

  private handlePickerCancel() {
    this.showPicker = false;
  }
}
